package com.amigo.online.provider.user.controller;

import javax.annotation.Resource;

import com.amigo.online.common.core.response.Result;
import com.amigo.online.common.param.dto.video.CheckVersionDto;
import com.amigo.online.provider.user.mapper.AppVersionMapper;
import com.amigo.online.provider.user.model.entity.AppVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.base.controller.BaseController;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.core.security.IgnoreSecurity;
import com.amigo.online.common.param.dto.login.ExistDto;
import com.amigo.online.common.param.dto.login.LoginByIdDto;
import com.amigo.online.common.param.dto.login.LoginDto;
import com.amigo.online.common.param.dto.login.RegisterDto;
import com.amigo.online.common.param.result.LoginInfo;
import com.amigo.online.common.util.CommonValidator;
import com.amigo.online.provider.user.exception.UserException;
import com.amigo.online.provider.user.service.UserService;
import com.amigo.online.provider.user.util.StandardizePhoneUtil;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 登录相关
 *
 * @author amigo
 */
@RestController
@RequestMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class LoginController extends BaseController {

    @Resource
    private UserService userService;

    @Autowired
    private AppVersionMapper appVersionMapper;
    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @IgnoreSecurity
    @PostMapping(value = "/user/login")
    public ResponseEntity<Response> login(@RequestBody LoginDto loginDto) {
        if (!CommonValidator.validate(loginDto)) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        Double[] point = new Double[2];
        point[0] = Double.parseDouble(loginDto.getLongitude());
        point[1] = Double.parseDouble(loginDto.getLatitude());
        LoginInfo info = userService.login(loginDto.getType(), loginDto.getUsername(), loginDto.getPassword(), point, loginDto.getPlatform(), loginDto.getVersion(), loginDto.getDevice());
        return success(info);
    }

    @IgnoreSecurity
    @PostMapping(value = "/login")
    public ResponseEntity<Response> login2(@RequestBody LoginDto loginDto) {
        if (!CommonValidator.validate(loginDto)) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        Double[] point = new Double[2];
        point[0] = Double.parseDouble(loginDto.getLongitude());
        point[1] = Double.parseDouble(loginDto.getLatitude());
        LoginInfo info = userService.login(loginDto.getType(), loginDto.getUsername(), loginDto.getPassword(), point, loginDto.getPlatform(), loginDto.getVersion(), loginDto.getDevice());
        return success(info);
    }
    /**
     * 创建用户
     * @param registerDto
     * @param lng
     * @param lat
     * @return
     */
    @IgnoreSecurity
    @PostMapping(value = "/user/register")
    public ResponseEntity<Response> resiter(@RequestBody RegisterDto registerDto, @RequestHeader(value = "lng", defaultValue = "0") String lng, @RequestHeader(value = "lat", defaultValue = "0") String lat) {
        if (!CommonValidator.validate(registerDto)) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        Double[] point = new Double[2];
        point[0] = Double.parseDouble(lng);
        point[1] = Double.parseDouble(lat);
        LoginInfo info = userService.register(registerDto.getMobilephone(), registerDto.getCountryCode(), registerDto.getCode(), registerDto.getPassword(), registerDto.getPassword2(),  registerDto.getRegisterCode(), point);
        //当邀请码使用过多发送邮件给BOSS
        userService.checkInvite();
        return success(info);
    }

    @IgnoreSecurity
    @PostMapping(value = "/user/exist")
    public ResponseEntity<Response> exist(@RequestBody ExistDto existDto) {
        if (!CommonValidator.validate(existDto)) {
            throw new UserException(StatusCode.BAD_REQUEST);
        }
        return success(userService.accountExist(existDto.getAccount(), existDto.getType()));
    }

    @IgnoreSecurity
    @PostMapping(value = "/user/loginById")
    public ResponseEntity<Response> loginById(@RequestBody LoginByIdDto loginDto) {
        JSONObject info = userService.loginById(loginDto);
        return success(info);
    }

    /**
     * 校验app版本
     * @param dto
     * @return
     */
    @IgnoreSecurity
    @PostMapping("/checkVersion")
    public Result checkVersion(@RequestBody CheckVersionDto dto) {
        boolean isLatestVersion = true;
        String downloadUrl = "";
        boolean isForceUpdate = false;

        Example example = new Example(AppVersion.class);
        example.createCriteria().andGreaterThan("id", dto.getVersion());
        example.setOrderByClause("id desc");
        List<AppVersion> appVersions = appVersionMapper.selectByExample(example);
        if(!appVersions.isEmpty()){
            for (AppVersion appVersion: appVersions){
                if (appVersion.getIsForceUpdate()){
                    isForceUpdate = true;
                }
            }
            isLatestVersion = false;
            downloadUrl = appVersions.get(0).getUrl();
        }


        Map<String, Object> map = new HashMap<>();
        map.put("isLatestVersion", isLatestVersion);
        map.put("downloadUrl", downloadUrl);
        map.put("isForceUpdate", isForceUpdate);
        return Result.success(map);
    }
}
